<?php
	
	include_once "../../../config.inc.php";
	
	$id = $_GET["id"];
					
	$deleteQuery = "";
	$connection = pg_connect("host=".W." port=".V." dbname=".Z." user=".Y." password=".X) or die ("Falló la conexion");
	
	// Id,email de usuario y nombre de app.
	
	$selectQuery = "SELECT user_id from applications where app_id = ".$id;
	$select = pg_query($connection,$selectQuery);
	
		while ($row = pg_fetch_row($select))
			$usrId = $row[0];
			
	$selectQuery = "SELECT user_email from users where user_id = ".$usrId;
	$select = pg_query($connection,$selectQuery);
	
		while ($row = pg_fetch_row($select))
			$email = $row[0];
			
	$selectQuery = "SELECT app_name from applications where app_id = ".$id;
	$select = pg_query($connection,$selectQuery);
	
		while ($row = pg_fetch_row($select))
			$appName = $row[0];
	
	// Secciones de esa aplicacion, borrando todos sus elementos y ella misma tambien.
	
	$selectQuery = "SELECT sec_id from sections where app_id = ".$id;
	$select = pg_query($connection,$selectQuery);
	
		while ($row = pg_fetch_row($select)){
			
			$deleteQuery = "DELETE FROM ELEMENT_TEXT WHERE SEC_ID = ".$row[0].";";
						    $delete = pg_query($connection,$deleteQuery);			
							
	  		$deleteQuery = "DELETE FROM MENU_ELEMENT WHERE SEC_ID = ".$row[0].";";
						    $delete = pg_query($connection,$deleteQuery);
							
							$deleteQuery = "DELETE FROM MENU_LIST WHERE SEC_ID = ".$row[0].";";
						    $delete = pg_query($connection,$deleteQuery);			
		
							
	 		$deleteQuery = "DELETE FROM IMAGE_ELEMENT WHERE SEC_ID = ".$row[0].";";
						    $delete = pg_query($connection,$deleteQuery);
							
							$deleteQuery = "DELETE FROM GALLERY_ELEMENT WHERE SEC_ID = ".$row[0].";";
						    $delete = pg_query($connection,$deleteQuery);
		
	  		$deleteQuery = "DELETE FROM SECTIONS WHERE SEC_ID = ".$row[0].";";
						    $delete = pg_query($connection,$deleteQuery);	
				
		}
	
	//Finalmente se borra la aplicación
		
	$deleteQuery = "DELETE FROM APPLICATIONS WHERE APP_ID = ".$id.";";
	$delete = pg_query($connection,$deleteQuery);			
	deleteDir("../../".ROUTE_APPLICATIONS_USERS.$email."/Applications/".$appName);	
	echo $usrId;

?>

<?php

	function deleteDir($dir) 
	{ 
	   if (substr($dir, strlen($dir)-1, 1) != '/') 
		   $dir .= '/';  
	   if ($handle = opendir($dir)) 
	   { 
		   while ($obj = readdir($handle)) 
		   { 
			   if ($obj != '.' && $obj != '..') 
			   { 
				   if (is_dir($dir.$obj)) 
				   { 
					   if (!deleteDir($dir.$obj)) 
						   return false; 
				   } 
				   elseif (is_file($dir.$obj)) 
				   { 
					   if (!unlink($dir.$obj)) 
						   return false; 
				   } 
			   } 
		   } 
	
		   closedir($handle); 
	
		   if (!@rmdir($dir)) 
			   return false; 
		   return true; 
	   } 
	   return false; 
	} 

?>